package polimi.disttest.manager;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ProcessWrapper {
	
	private Process p;
	private String id;
	
	public String getId() {
		return id;
	}

	public ProcessWrapper(String id, String command) throws IOException {
		this.id = id;
		//System.err.println("[" + id + "] executing: " + command);
		p = Runtime.getRuntime().exec(command);
	}
	
	public int exitValue() throws IllegalThreadStateException {
		return p.exitValue();
	}

	public void printResults() throws IllegalThreadStateException {
		if (p.exitValue()==0) {
			System.out.println("Process " + id + " execution: OK");
		} else {
			System.out.println("Process " + id + " execution: error " + p.exitValue());
		}
		
		BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
		try {
			String line=null;
			while ((line=reader.readLine()) != null) {
				System.out.println("[" + id + "] " + line);
			}
		} catch (IOException e) { }
		
		reader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
		try {
			String line=null;
			while ((line=reader.readLine()) != null) {
				System.err.println("[" + id + "] " + line);
			}
		} catch (IOException e) { }
		
	}
}
